package 动态数组;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author ycc
 * @date 2024/7/1
 */
public class Test {
    public static void main(String[] args) {
        System.out.println("hello list");
        List<User> list = new java.util.ArrayList<>();
        list.add(new User(1L, 0L, "user1"));
        list.add(new User(2L, 4L, "user2"));
        list.add(new User(3L, 5L, "user3"));
        list.add(new User(4L, 1L, "user4"));
        list.add(new User(5L, 2L, "user5"));
        list.add(new User(6L, 2L, "user6"));
        list.add(new User(7L, 0L, "user7"));

        List<User> list2 = test(list, 5L);
        System.out.println("查找上级处理为链条后");
        for (User user : list2) {
            System.out.println(user);
        }
    }

    public static List<User> test(List<User> list, Long id) {
        List<User> newList = new ArrayList<>();
        Map<Long, User> map = new ConcurrentHashMap<>();
        for(User user : list) {
            map.put(user.getId(), user);
        }

        User item = map.get(id);
        while (item != null) {
            newList.add(item);
            if(!item.getPid().equals(0L)) {
                item = map.get(item.getPid());
            } else {
                item = null;
            }
        }
        return newList;
    }
}
